<?php

namespace app\common\model\xiluedu;

use app\common\library\Auth;
use think\Db;
use think\Log;
use think\Model;
use function fast\array_get;


class UserCollection extends Model
{

    const TYPE_COURSE = 1;
    const TYPE_FORUM = 2;


    // 表名
    protected $name = 'xiluedu_user_collection';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [

    ];

    public function course(){
        return $this->belongsTo('Course','collection_id','id',[],'left')->setEagerlyType(1);
    }

    /**
     * @param int $userId
     * @param int $recordId
     * @param $type
     * @return bool|string true是已收藏状态, false是未收藏状态
     */
    public static function toggleCollection($userId, $recordId, $type) {
        try {
            Db::startTrans();
            $model = static::where('user_id', $userId)
                ->where('collection_type', $type)
                ->where('collection_id', $recordId)
                ->find();
            if ($model) {
                $model->delete();
                $result = false;
            } else {
                $model = new UserCollection([
                    'user_id' => $userId,
                    'collection_type' => $type,
                    'collection_id' => $recordId
                ]);
                if ($model->save() === false) {
                    Db::rollback();
                    return $model->getError();
                }
                $result = true;
            }
            $collectionCount = UserCollection::where('collection_type', $type)->where('collection_id', $recordId)->count();
            switch ($type) {
                case self::TYPE_COURSE:
                    Course::where('id', $recordId)->update(['collection_count' => $collectionCount]);
                    break;
                case self::TYPE_FORUM:
                    TopicForum::where('id', $recordId)->update(['collection_count' => $collectionCount]);
                    break;
            }
            Db::commit();
            return $result;
        }catch (\Exception $e) {
            Log::error($e->getMessage()."\n".$e->getTraceAsString());
            Db::rollback();
            return false;
        }
    }

    /**
     * 我的课程列表
     */
    public static function lists($params,$type=NULL){
        $auth = Auth::instance();
        $pagesize = array_get($params,'pagesize',10);
        return static::with(['course'=>function($query){
            $query->withField(['id','type','name','category_id','tag_ids','teacher_id','thumb_image','description','is_charge','(basic_num+real_num) total_num','collection_count','salesprice','play_count']);
        }])
            ->where('user_id',$auth->id)
            ->where('collection_type',$type)
            ->order('id','desc')
            ->paginate($pagesize);
    }

    /**
     * 用户是否已收藏
     * @param $userId
     * @param $recordId
     * @param $type
     * @return bool
     */
    public static function isFav($userId, $recordId, $type) {
        if(!$userId || !$recordId || !$type)
            return false;
        return static::where('user_id',$userId)
                ->where('collection_type',$type)
                ->where('collection_id',$recordId)->count() > 0;
    }

}
